import { domAddClass, domRemoveClass } from '@vimi/utils-tool'
import { setTheme } from '@/common/plugins/theme/themeSet'

export const themeMixin = {
  data() {
    return {
      themeLocal: '',
      theme: '',
    }
  },
  created() {
    setTheme(this.theme, this.themeLocal)
  },
}

export const progressBarMixin = {
  created() {
    this.progress()
  },
  methods: {
    progress() {
      this.$Progress.start()
      this.$router.beforeEach((to, from, next) => {
        if (to.meta.progress) {
          this.$Progress.parseMeta(to.meta.progress)
        }
        this.$Progress.start()
        next()
      })
      this.$router.afterEach(() => {
        this.$Progress.finish()
      })
    },
  },
}

export const logoutMixin = {
  methods: {
    logoutTo(path = '/login') {
      let host = window.location.host
      if (/localhost/.test(host)) {
        this.$router.push(path)
        // 清空store
        window.location.reload()
      } else {
        window.location.href = `${window.location.protocol}//${host}/#${path}`
      }
    },
  },
}

export const networkMixin = {
  data() {
    return {
      offlineCssName: 'g-network-offline',
      notifyInstance: null,
    }
  },

  computed: {
    isOnline() {
      return this.$store.getters.isOnline
    },
  },

  mounted() {
    window.addEventListener('offline', this.networkOfflineHandler)
    window.addEventListener('online', this.networkOnlineHandler)
  },

  beforeDestroy() {
    this.notifyInstance = null
    window.removeEventListener('offline', this.networkOnlineHandler)
    window.removeEventListener('online', this.networkOfflineHandler)
  },

  methods: {
    networkOnlineHandler() {
      if (this.isOnline) return
      this.networkChangeHandler(true)
      domRemoveClass(document.body, this.offlineCssName)
      this.notifyInstance = this.$notify({
        title: '网络提示',
        type: 'success',
        message: '网络已连接。',
      })
    },

    networkOfflineHandler() {
      this.networkChangeHandler(false)
      domAddClass(document.body, this.offlineCssName)
      this.notifyInstance = this.$notify({
        title: '网络提示',
        type: 'error',
        message: '网络已断开，请检查网络连接。',
        duration: 3e4,
      })
    },

    networkChangeHandler(isOnline) {
      this.notifyInstance && this.notifyInstance.close()
      this.$store.commit('isOnline', isOnline)
    },
  },
}
